/* eslint-disable @typescript-eslint/no-shadow */
/*
 * @Author       : 吴豪
 * @Date         : 2021-12-4 15:56:22
 * @FilePath     : \book-manage-front\src\pages\classificationManage\index.tsx
 * @Description  : 分类管理页面
 */

import { PageContainer } from '@ant-design/pro-layout';
import React, { useRef, useState } from 'react';
import { Button, message, Popconfirm, Space } from 'antd';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import type { ParamsType } from '@ant-design/pro-provider';
import { deleteClassification, getClassificationList } from '@/services/classification';
import { DownOutlined, RightOutlined } from '@ant-design/icons';
import CreateClassification from './classificationsComponents/CreateClassification';
import EditClassification from './classificationsComponents/EditClassification';
import styles from './index.less';
import type { ClassificationList } from '@/dataType';

/**
 * 分类管理页面，渲染分类列表，引用子级组件实现功能
 * @returns
 */
function ClassificationManage() {
  const actionRef = useRef<ActionType>();
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [isModalVisibleEdit, setIsModalVisibleEdit] = useState(false);
  const [aid, setAid] = useState(undefined);

  /**
   * 新增模态框的控制
   */
  const isShowModal = (show: boolean | ((prevState: boolean) => boolean)) => {
    setIsModalVisible(show);
  };

  /**
   * 修改模态框的控制
   */
  const isShowModalEdit = (show: boolean | ((prevState: boolean) => boolean), aid: any) => {
    setAid(aid);
    setIsModalVisibleEdit(show);
  };

  /**
   * 删除分类
   * @param aid
   */
  const confirm = async (aid: number) => {
    const params = {
      aid: aid,
    };
    const response = await deleteClassification(params);
    if (response) {
      message.success('删除成功！');
      actionRef.current?.reload();
    }
  };
  function cancel() {
    message.error('取消删除！');
  }

  /**
   * 获取分类列表
   * @param params
   * @returns
   */
  const getClassificationDate = async (
    params: ParamsType & {
      pageSize?: number | undefined;
      current?: number | undefined;
      keyword?: string | undefined;
    },
  ) => {
    const param = {
      searchKey: params.searchKey,
      page: params.current!,
      pageSize: params.pageSize!,
    };
    const response = await getClassificationList(param);
    return {
      data: response.list,
      success: true,
      total: response.rowsNum,
    };
  };

  /**
   * 设计表格
   */
  const columns: ProColumns<ClassificationList>[] = [
    {
      title: '名称',
      dataIndex: 'name',
      hideInSearch: true,
    },
    {
      title: '分类名称',
      dataIndex: 'searchKey',
      copyable: true,
      ellipsis: true,
      hideInTable: true,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '此项为必填项',
          },
        ],
      },
    },
    {
      title: '操作',
      dataIndex: '',
      hideInSearch: true,
      render: (_, record) => (
        <Space>
          <Button
            type="link"
            className={styles.button}
            onClick={() => isShowModalEdit(true, record.aid)}
          >
            修改
          </Button>
          <Popconfirm
            disabled={!record.canDelete}
            placement="topRight"
            title="你确认要删除该项数据吗??"
            onConfirm={() => confirm(record.aid)}
            onCancel={cancel}
            okText="确认"
            cancelText="取消"
          >
            <Button
              type="link"
              className={styles.button}
              onClick={() => {}}
              disabled={!record.canDelete}
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <PageContainer
      header={{
        title: '分类管理',
        ghost: true,
        breadcrumb: {
          routes: [
            {
              path: '',
              breadcrumbName: '组织构架',
            },
            {
              path: '',
              breadcrumbName: '分类管理',
            },
          ],
        },
      }}
    >
      <ProTable<ClassificationList>
        columns={columns}
        actionRef={actionRef}
        request={(param) => getClassificationDate(param)}
        editable={{
          type: 'multiple',
        }}
        expandable={{
          expandIcon: ({ expanded, onExpand, record }) =>
            record.children.length ? (
              expanded ? (
                <DownOutlined onClick={(e) => onExpand(record, e)} style={{ margin: '0px 15px' }} />
              ) : (
                <RightOutlined
                  onClick={(e) => onExpand(record, e)}
                  style={{ margin: '0px 15px' }}
                />
              )
            ) : (
              <span className={styles.span} />
            ),
        }}
        columnsState={{
          persistenceKey: 'pro-table-singe-demos',
          persistenceType: 'localStorage',
        }}
        rowKey="aid"
        search={{
          span: 6,
        }}
        options={{
          density: false,
          setting: false,
          fullScreen: true,
        }}
        pagination={{
          pageSize: 10,
          size: 'default',
          showTotal: undefined,
        }}
        dateFormatter="string"
        headerTitle="分类列表"
        toolBarRender={() => [
          <Button key="button" type="primary" onClick={() => isShowModal(true)}>
            新增
          </Button>,
        ]}
      />

      {/* 引用新增分类组件 */}
      <CreateClassification
        isModalVisible={isModalVisible}
        isShowModal={isShowModal}
        actionRef={actionRef}
      />

      {/* 引用修改分类组件 */}
      <EditClassification
        isModalVisible={isModalVisibleEdit}
        isShowModal={isShowModalEdit}
        actionRef={actionRef}
        aid={aid}
      />
    </PageContainer>
  );
}

export default ClassificationManage;
